const app = getApp();

Page({
  data: {
    conversations: [],
    loading: false
  },

  onLoad() {
    console.log('💬 Chat list page loaded');
    this.checkAndLoad();
  },

  onShow() {
    console.log('💬 Chat list page shown');
    this.checkAndLoad();
  },

  onPullDownRefresh() {
    this.loadConversations().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  checkAndLoad() {
    if (!app.globalData.userInfo) {
      console.log('❌ User not logged in, redirecting to login');
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/user/login/login' });
          }, 1500);
        }
      });
      return;
    }
    this.loadConversations();
  },

  async loadConversations() {
    this.setData({ loading: true });
    
    try {
      console.log('📞 Loading conversations...');
      const conversations = await app.request('/messages/conversations', 'GET');
      console.log('✅ Conversations loaded:', conversations);
      
      this.setData({ 
        conversations: conversations || [],
        loading: false 
      });
    } catch (error) {
      console.error('❌ Load conversations error:', error);
      this.setData({ loading: false });
      
      if (error.error && error.error.includes('登录')) {
        wx.showToast({ 
          title: error.error, 
          icon: 'none',
          success: () => {
            setTimeout(() => {
              wx.navigateTo({ url: '/pages/user/login/login' });
            }, 1500);
          }
        });
      } else {
        wx.showToast({ title: '加载会话失败', icon: 'none' });
      }
    }
  },

  onConversationTap(e) {
    const user = e.currentTarget.dataset.user;
    console.log('👤 Starting conversation with:', user);
    
    if (!user || !user._id) {
      wx.showToast({ title: '用户信息错误', icon: 'none' });
      return;
    }

    wx.navigateTo({
      url: `/pages/chat/chat?toUserId=${user._id}&toUserName=${user.username}`
    });
  },

  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / 86400000);

    if (days === 0) {
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  }
});